<template>
  <el-dialog title="新增用户" :visible.sync="dialogFormVisible" @close="resetForm">
    <el-form ref="editForm" :model="editForm" :rules="editRules" label-width="120px">
      <el-form-item label="账号" prop="userName">
        <el-input v-model="editForm.userName" placeholder="请输入账号" clearable style="width: 260px"></el-input>
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input v-model="editForm.password" placeholder="请输入原密码" clearable show-password style="width: 260px"></el-input>
      </el-form-item>
      <el-form-item label="角色" prop="role">
        <el-select v-model="editForm.role" placeholder="请选择角色" clearable style="width: 260px">
          <el-option v-for="item in roleList" :key="item.role" :label="item.name" :value="item.role">
          </el-option>
        </el-select>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="resetForm">取 消</el-button>
      <el-button type="primary" @click="confirmEdit" :loading="editLoading">确 定</el-button>
    </div>
  </el-dialog>
</template>
<script>
import api from '../api/index.js';
export default {
  props: {},
  computed: {},
  data() {
    return {
      dialogFormVisible: false,
      editForm: {
        userName: '',
        password: '',
        role: '',
      },
      roleList: this.$config.USER_ROLE_LIST,
      editLoading: false,
      editRules: {
        userName: [
          { required: true, message: '请输入账号', trigger: 'blur' },
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, message: '密码长度不能少于6个字符', trigger: 'blur' }
        ],
        role: [
          { required: true, message: '请选择角色', trigger: 'submit' },
        ],
      },
    }
  },
  watch: {},
  created() {
  },
  mounted() { },
  methods: {
    open() {
      this.dialogFormVisible = true;
    },
    confirmEdit() {
      this.$refs['editForm'].validate((result) => {
        if (result) {
          this.editLoading = true;
          api.addUser({
            userName: this.editForm.userName,
            password: this.$utils.encrypt(this.editForm.password),
            role: this.editForm.role,
          })
            .then((res) => {
              this.editLoading = false;
              if (res.success) {
                this.dialogFormVisible = false;
                this.$refs['editForm'].resetFields();
                this.$emit('success');
              } else {
                this.$message.error('新增用户失败：' + (res.message || ''));
              }
            })
            .catch((e) => {
              this.editLoading = false;
              this.$log.error('新增用户失败，错误信息为：', e);
            });
        }
      });
    },
    resetForm() {
      this.$refs['editForm'].resetFields();
      this.dialogFormVisible = false;
    },
  }
}
</script>
<style lang="scss" scoped></style>